<?php
namespace app\forum\model;
use app\base\model\BaseModel;
/**
 * 帖子操作
 */
class ThreadModel extends BaseModel {
    //完成
    protected $_auto = array (
        //全部
        array('description','getDescription',3,'callback'), //描述
        array('image','getImage',3,'callback'), //形象图
        //增加
        array('plate_id','intval',1,'function'), //板块ID
        array('post_time','time',1,'function'), //时间
        array('post_user',USER_ID,1,'string'), //发帖用户
        array('status',1,1,'string'),  //状态
        //编辑
        array('thread_id','intval',2,'function'), //内容ID
        array('edit_user',USER_ID,2,'string'), //编辑用户
        array('edit_time','time',2,'function'), //编辑时间
     );
    //验证
    protected $_validate = array(
        //全部验证
        array('title','1,255', '标题只能为1~250个字符', 1 , 'length'),
        array('plate_id','require', '请选择板块', 1 ,'regex'),
        //编辑验证
        array('thread_id','require', '内容ID获取不正确', 1 ,'regex',2),
    );

    /**
     * 获取列表
     * @return array 列表
     */
    public function loadList($where = array(), $limit = 0, $order = 'A.post_time desc,A.thread_id desc'){

        $pageList = $this->table("thread as A")
                    ->join('{pre}plate as B ON A.plate_id = B.plate_id')
                    ->join('{pre}user as C ON A.post_user = C.user_id')
                    ->join('{pre}user as D ON A.reply_user = D.user_id','left')
                    ->field('A.*,B.name as class_name,B.app,B.parent_id,C.username as post_username,D.username as reply_username')
                    ->where($where)
                    ->limit($limit)
                    ->order($order)
                    ->select();
        //处理数据类型
        $list=array();
        if(!empty($pageList)){
            $i = 0;
            foreach ($pageList as $key=>$value) {
                $list[$key]=$value;
                $list[$key]['app']=strtolower($value['app']);
                $list[$key]['aurl'] = target('forum/Thread')->getUrl($value);
                $list[$key]['curl'] = target('forum/Plate')->getUrl($value);
                $list[$key]['i'] = $i++;
            }
        }
        return $list;
    }

    /**
     * 获取数量
     * @return int 数量
     */
    public function countList($where = array()){
        return $this->table("thread as A")
                    ->join('{pre}plate as B ON A.plate_id = B.plate_id')
                    ->join('{pre}user as C ON A.post_user = C.user_id')
                    ->join('{pre}user as D ON A.reply_user = D.user_id','left')
                    ->where($where)
                    ->count();
    }
    
    /**
     * 获取信息
     * @param array $where 条件
     * @return array 信息
     */
    public function getWhereInfo($where){
        $info = $this->table("thread as A")
                    ->join('{pre}plate as B ON A.plate_id = B.plate_id')
                    ->join('{pre}user as C ON A.post_user = C.user_id')
                    ->join('{pre}user as D ON A.reply_user = D.user_id','left')
                    ->field('A.*,B.name as class_name,B.app,B.parent_id,C.username as post_username,D.username as reply_username')
                    ->field('A.*,B.name as class_name,B.app,B.parent_id')
                    ->where($where)
                    ->find();
        if(!empty($info)){
            $info['app'] = strtolower($info['app']);
        }
        return $info;
    }

    /**
     * 获取置顶列表
     * @param array $where 条件
     * @return array 信息
     */
    public function getTopList($plateId)
    {
        $where = array();
        $where['A.plate_id'] = $plateId;
        $where['A.type_top'] = 1;
        $plate = target('forum/Thread')->loadList($where);
        $where = array();
        $where['A.type_top'] = 2;
        $forum = target('forum/Thread')->loadList($where);
        return array_merge($forum,$plate);
    }

    /**
     * 获取信息
     * @param int $threadId ID
     * @return array 信息
     */
    public function getInfo($threadId)
    {
        $map = array();
        $map['A.thread_id'] = $threadId;
        $info = $this->getWhereInfo($map);
        if(empty($info)){
            $this->error = '帖子不存在！';
        }
        return $info;
    }

    /**
     * 更新信息
     * @param string $type 更新类型
     * @return bool 更新状态
     */
    public function saveData($type = 'add',$field=''){
        $data = $this->create();
        if(!$data){
            return false;
        }
        if($type == 'add'){
            //发帖间隔
            $where = array();
            $where['post_user'] = USER_ID;
            $info = $this->where($where)->order('thread_id desc')->find();
            if($info){
                if($info['title'] == $data['title']){
                    $this->error = '请不要发布重复内容！';
                    return false;
                }
                if(($info['post_time']+60) > time()){
                    $this->error = '抱歉，1分钟内禁止再次发帖，请稍等！';
                    return false;
                }
            }
            //保存基本信息
            return $this->into($field)->add($data);
        }
        if($type == 'edit'){
            if(empty($data['thread_id'])){
                return false;
            }
            $status = $this->into($field)->save();
            if($status === false){
                return false;
            }else{
                return true;
            }
        }
        return false;
    }

    /**
     * 修改信息
     * @param int $threadId ID
     * @return bool 删除状态
     */
    public function editData($data){
        $status = $this->save($data);
        if($status === false){
            return false;
        }else{
            return true;
        }
    }

    /**
     * 删除信息
     * @param int $threadId ID
     * @return bool 删除状态
     */
    public function delData($threadId){
        $map = array();
        $map['thread_id'] = $threadId;
        //删除回复
        target('forum/Reply')->where($map)->delete();
        //删除帖子
        return $this->where($map)->delete();
    }

    /**
     * 提取描述
     * @return string 内容描述
     */
    public function getDescription(){
        //获取变量
        $description = request('post.description');
        $content = request('post.content');
        //处理数据
        if(empty($content)){
            return $description;
        }
        $description = \app\forum\util\Ubb::ubbToHtml($content);
        $description = strip_tags($description);
        $description = str_replace(array("\r\n","\t",'&ldquo;','&rdquo;','&nbsp;'), '', $description);
        $description = substr($description, 0,250);
        return $description;
    }

    /**
     * 提取形象图
     * @return string 内容形象图
     */
    public function getImage(){
        $content = request('post.content');
        return target('forum/ContentTools')->getImage($content, 1);
    }
    /**
     * 获取内容URL
     * @param int $info 栏目信息
     * @return bool 删除状态
     */
    public function getUrl($info)
    {
        return url(strtolower($info['app']).'/Thread/index',array('thread_id'=>$info['thread_id']));
    }

    /**
     * 验证TOKEN
     * @param string $key 验证信息
     * @param string $token 验证信息
     * @return bool 状态
     */
    public function validToken($key, $token)
    {
        $token = session('token_'.$key);
        if(empty($token)){
            return false;
        }
        $ssToken = trim($token);
        if($token<>$ssToken){
            return false;
        }
        session('token_'.$key,' ');
        return true;
    }

    /**
     * 生成TOKEN
     * @param string $key 验证信息
     * @return string token
     */
    public function setToken($key)
    {
        $token = md5(microtime(true));
        session('token_'.$key,$token);
        return $token;
    }

}
